package com.leha.forum.lehare.response;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 接口响应结果类
 * 所有的接口都应该返回这个类的实例
 * @param <T> Data Type
 */
public class Result<T> {
    private int code;
    private String message;
    private T data;

    public static final int CODE_SUCCESS = 200;
    public static final int CODE_ERR_BAD_REQUEST = 400;
    public static final int CODE_ERR_NOT_AUTHORIZED = 401;
    public static final int CODE_ERR_FORBIDDEN = 403;
    public static final int CODE_ERR_INTERNAL_ERROR = 500;

    public static final int CODE_ACTION_LOGIN_INVALID = 601;

    public static final int CODE_SERVICE_ERR_FORBIDDEN = 40003;

    public static final String MESSAGE_SUCCESS_DEFAULT = "";

    public static final int CODE_AUTH_CONSENT_INVALID = 60000;


    public Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static <T> Result<T> success() {
        return new Result<T>(CODE_SUCCESS, "", null);
    }

    public static <T> Result<T> success(T data) {
        return new Result<T>(CODE_SUCCESS, "", data);
    }

    public static <T> Result<T> success(String message, T data) {
        return new Result<T>(CODE_SUCCESS, message, data);
    }

    public static Result<Void> failed(int code, String message) {
        return new Result<>(code, message, null);
    }

    public String toJSONString() {
        try {
            return new ObjectMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "{}";
        }
    }
}
